<template>
  <div class="permission-tracker">
    <!-- 终端风格头部 -->
    <div class="terminal-header">
      <div class="terminal-tabs">
        <span class="terminal-tab active">权限追踪模块</span>
      </div>
      <!-- 面包屑导航 - 黑客风格 -->
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-hacker">
        <el-breadcrumb-item :to="{ path: '/' }">NEXUS操作系统</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理模块</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 控制面板 -->
      <el-card class="hacker-card">
        <div class="card-header">
          <span class="card-title">系统.权限.控制面板</span>
        </div>
        <el-form :inline="true" :model="searchData" class="search-form">
          <el-form-item label="权限名称">
          <el-input v-model="searchData.permissionName" placeholder="搜索权限" class="hacker-input" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getPermissions" class="hacker-button primary">搜索</el-button>
          <el-button type="success" @click="addPermission" class="hacker-button success">添加</el-button>
        </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 权限列表 -->
      <el-card class="hacker-card" style="margin-top: 15px;">
        <div class="card-header">
          <span class="card-title">系统.权限.数据表格</span>
          <span class="system-info">条目数: {{ page.totalCount }}</span>
        </div>
        
        <div class="table-wrapper">
          <el-table :data="permissionData" border class="hacker-table">
            <el-table-column type="index" label="ID" align="center" width="70" />
            <el-table-column prop="permissionName" label="权限名称" align="center" />
            <el-table-column prop="permissionUrl" label="权限URL" align="center" />
            <el-table-column label="操作" align="center">
              <template #default="scoped">
                <el-button type="primary" size="small" @click="editPermission(scoped.row)" class="hacker-button small">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页控件 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalCount"
            class="hacker-pagination"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 添加/编辑权限弹窗 - 黑客风格 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" draggable class="hacker-dialog">
      <div class="dialog-header-hacker">
        <div class="dialog-dots">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
        </div>
        <h3 class="dialog-title-text">{{ dialogTitle }}</h3>
      </div>
      
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="addRules" label-width="100px" class="hacker-form">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="ruleForm.permissionName" placeholder="输入权限名称" class="hacker-input" />
        </el-form-item>
        <el-form-item label="权限URL" prop="permissionUrl">
          <el-input v-model="ruleForm.permissionUrl" placeholder="输入权限URL" class="hacker-input" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer-hacker">
            <el-button @click="dialogVisible = false" class="hacker-button cancel">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" class="hacker-button primary">确认</el-button>
          </span>
      </template>
    </el-dialog>
    
    <!-- 数字雨背景效果 -->
    <div class="matrix-rain"></div>
    
    <!-- 系统日志面板 -->
    <div class="system-log-panel">
      <div class="log-header">
        <span class="log-title">系统.日志</span>
        <span class="clear-log" @click="clearLog">清空</span>
      </div>
      <div class="log-content" ref="logContent">
        <div v-for="(log, index) in systemLogs" :key="index" class="log-entry">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch, nextTick } from 'vue'
import { ElMessageBox } from 'element-plus';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCounterStore } from "@/stores/counter"
import { dataRead, dataWrite } from '@/Utils/Http';
import { ArrowRight } from '@element-plus/icons-vue'

// 类型定义
interface RuleForm  {
    permissionId: number;
    permissionName: string;
    permissionUrl: string;
}

// 系统日志类型
interface SystemLog {
    time: string;
    message: string;
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    permissionId: 0,
    permissionName: '',
    permissionUrl: ''
})

// 变量初始化
const counter = useCounterStore();
const router = useRouter();
const permissionData = ref<any>([]);
const searchData = reactive({
    permissionName: ''
});
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalCount: 0,
    pageCount: 0
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加权限');
const logContent = ref<HTMLDivElement>();
const systemLogs = ref<SystemLog[]>([]);

// 添加表单验证规则
const addRules  = reactive<FormRules<RuleForm>>({
    permissionName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' }
    ],
    permissionUrl: [
        { required: true, message: '请输入权限URL', trigger: 'blur' }
    ]
});

// 系统日志函数
const systemLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString('zh-CN', {
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    
    const logEntry: SystemLog = {
        time: timestamp,
        message: message
    };
    
    systemLogs.value.push(logEntry);
    
    // 保持日志滚动到底部
    nextTick(() => {
        if (logContent.value) {
            logContent.value.scrollTop = logContent.value.scrollHeight;
        }
    });
    
    console.log(`[${timestamp}] ${message}`);
};

// 清除日志
const clearLog = () => {
    systemLogs.value = [];
    systemLog('系统: 日志已清空');
};

// 生命周期钩子
onMounted(() => {
    systemLog('系统: 权限模块已初始化');
    systemLog('系统: 正在加载权限数据');
    getPermissions();
    
    // 初始化数字雨效果
    initMatrixRain();
});

// 初始化数字雨效果
const initMatrixRain = () => {
    const container = document.querySelector('.permission-tracker')
    if (!container) return
    
    const matrixRain = document.querySelector('.matrix-rain')
    if (!matrixRain) return
    
    // 清除已有字符
    matrixRain.innerHTML = ''
    
    const chars = '01PERMISSIONACCESSUSERROLEMODULE';
    
    // 创建100个随机字符
    for (let i = 0; i < 100; i++) {
        const charElement = document.createElement('div')
        charElement.classList.add('matrix-char')
        charElement.textContent = chars[Math.floor(Math.random() * chars.length)]
        charElement.style.left = `${Math.random() * 100}%`
        charElement.style.top = `${Math.random() * 100}%`
        charElement.style.fontSize = `${Math.random() * 8 + 4}px`
        charElement.style.animationDuration = `${Math.random() * 10 + 10}s`
        charElement.style.animationDelay = `${Math.random() * 5}s`
        matrixRain.appendChild(charElement)
    }
};

// 获取权限列表
const getPermissions = () => {
    systemLog(`系统: 查询权限中 [名称: ${searchData.permissionName || '全部'}]`);
    
    dataRead.get('/BaseData/PermissionQuery', {
        params: {
            permissionName: searchData.permissionName,
            PageIndex: page.PageIndex,
            PageSize: page.PageSize
        } 
    }).then(res => {
        permissionData.value = res.data.data.data;
        page.totalCount = res.data.data.totalCount;
        page.pageCount = res.data.data.pageCount;
        systemLog(`系统: 权限数据已加载 [数量: ${res.data.data.totalCount}]`);
    }).catch(err => {
        ElMessage.error('系统错误: 加载权限失败');
        systemLog(`错误: 加载权限失败 - ${err}`);
    });
};

watch(page, () => {
    getPermissions()
});

// 添加权限
const addPermission = () => {
    dialogTitle.value = '添加权限';
    ruleForm.permissionId = 0;
    ruleForm.permissionName = '';
    ruleForm.permissionUrl = '';
    dialogVisible.value = true;
    systemLog('系统: 正在打开添加权限对话框');
};

// 编辑权限
const editPermission = (row: any) => {
    dialogTitle.value = '编辑权限';
    Object.assign(ruleForm, row);
    dialogVisible.value = true;
    systemLog(`系统: 正在打开编辑权限对话框 [ID: ${row.permissionId}]`);
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  
  await formEl.validate((valid, fields) => {
    if (valid) {
        systemLog(`系统: 提交权限表单中 [模式: ${ruleForm.permissionId == 0 ? '添加' : '编辑'}]`);
        
        if (ruleForm.permissionId == 0) {
            // 添加权限
            dataWrite.post('/BaseData/AddPermission', ruleForm).then(res => {
                if (res.data.code == 300) {
                    ElMessage.success('系统: 权限添加成功');
                    systemLog(`系统: 权限已添加 [名称: ${ruleForm.permissionName}]`);
                    dialogVisible.value = false;
                    getPermissions();
                } else if (res.data.data == -1) {
                    ElMessage.error(res.data.message);
                    systemLog(`错误: 添加权限失败 - ${res.data.message}`);
                } else {
                    ElMessage.error('系统错误: 添加权限失败');
                    systemLog('错误: 添加权限时发生意外错误');
                }
            }).catch(err => {
                ElMessage.error('系统错误: 网络连接失败');
                systemLog(`错误: 网络连接失败 - ${err}`);
            });
        } else {
            // 修改权限
            dataWrite.post('/BaseData/UpdPermission', ruleForm).then(res => {
                if (res.data.code == 400) {
                    ElMessage.success('系统: 权限更新成功');
                    systemLog(`系统: 权限已更新 [ID: ${ruleForm.permissionId}]`);
                    dialogVisible.value = false;
                    getPermissions();
                } else if (res.data.data == -1) {
                    ElMessage.error(res.data.message);
                    systemLog(`错误: 更新权限失败 - ${res.data.message}`);
                } else {
                    ElMessage.error('系统错误: 更新权限失败');
                    systemLog('错误: 更新权限时发生意外错误');
                }
            }).catch(err => {
                ElMessage.error('系统错误: 网络连接失败');
                systemLog(`错误: 网络连接失败 - ${err}`);
            });
        }
    } else {
        systemLog('系统: 表单验证失败');
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped>
/* 权限追踪器容器 */
.permission-tracker {
  width: 100%;
  min-height: 100vh;
  background-color: var(--hacker-dark);
  color: var(--hacker-text);
  font-family: 'Courier New', monospace;
  position: relative;
  overflow: hidden;
  /* 黑客风格网格背景 */
  background-image: 
    linear-gradient(rgba(0, 255, 65, 0.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 65, 0.03) 1px, transparent 1px);
  background-size: 20px 20px;
}

/* 终端风格头部 */
.terminal-header {
  background-color: var(--hacker-panel);
  border-bottom: 1px solid var(--hacker-border);
  padding: 10px 20px;
  box-shadow: 0 2px 10px rgba(0, 255, 65, 0.1);
}

.terminal-tabs {
  margin-bottom: 8px;
}

.terminal-tab {
  display: inline-block;
  padding: 5px 15px;
  background-color: var(--hacker-panel-dark);
  border: 1px solid var(--hacker-border);
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.terminal-tab.active {
  background-color: var(--hacker-dark);
  color: var(--hacker-green);
  border-top: 2px solid var(--hacker-green);
}

/* 面包屑导航 */
.breadcrumb-hacker {
  font-size: 11px;
}

.breadcrumb-hacker .el-breadcrumb__item {
  color: var(--hacker-text);
}

.breadcrumb-hacker .el-breadcrumb__item.is-active {
  color: var(--hacker-green);
}

/* 主内容区 */
.main-content {
  padding: 20px;
  position: relative;
  z-index: 10;
}

/* 黑客风格卡片 */
.hacker-card {
  background-color: var(--hacker-panel);
  border: 1px solid var(--hacker-border);
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 255, 65, 0.05);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: var(--hacker-panel-dark);
  border-bottom: 1px solid var(--hacker-border);
  margin: -15px -15px 15px -15px;
}

.card-title {
  font-size: 12px;
  font-weight: bold;
  color: var(--hacker-green);
  text-transform: uppercase;
  letter-spacing: 1px;
}

.system-info {
  font-size: 11px;
  color: var(--hacker-text);
}

/* 搜索表单 */
.search-form {
  margin-top: 10px;
}

.search-form .el-form-item__label {
  color: var(--hacker-text);
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* 黑客风格输入框 */
.hacker-input {
  background-color: var(--hacker-panel-dark);
  border: 1px solid var(--hacker-border);
  color: var(--hacker-text);
  font-family: 'Courier New', monospace;
  transition: all 0.3s ease;
}

.hacker-input:focus {
  border-color: var(--hacker-green);
  box-shadow: 0 0 8px var(--hacker-green-glow);
}

/* 黑客风格按钮 */
.hacker-button {
  background-color: transparent;
  border: 1px solid var(--hacker-border);
  color: var(--hacker-text);
  font-family: 'Courier New', monospace;
  text-transform: uppercase;
  font-size: 11px;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.hacker-button:hover {
  border-color: var(--hacker-green);
  color: var(--hacker-green);
  box-shadow: 0 0 8px var(--hacker-green-glow);
}

.hacker-button.primary {
  background-color: var(--hacker-green-dark);
  border-color: var(--hacker-green);
  color: var(--hacker-dark);
}

.hacker-button.primary:hover {
  background-color: var(--hacker-green);
  box-shadow: 0 0 10px var(--hacker-green-glow);
}

.hacker-button.success {
  background-color: transparent;
  border-color: var(--hacker-green);
  color: var(--hacker-green);
}

.hacker-button.success:hover {
  background-color: var(--hacker-green);
  color: var(--hacker-dark);
  box-shadow: 0 0 10px var(--hacker-green-glow);
}

.hacker-button.cancel {
  background-color: transparent;
  border-color: var(--hacker-red);
  color: var(--hacker-red);
}

.hacker-button.cancel:hover {
  background-color: var(--hacker-red);
  color: var(--hacker-dark);
}

.hacker-button.small {
  padding: 2px 10px;
  font-size: 10px;
}

/* 表格包装器 */
.table-wrapper {
  overflow-x: auto;
}

/* 黑客风格表格 */
.hacker-table {
  background-color: var(--hacker-panel-dark);
  color: var(--hacker-text);
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.hacker-table thead {
  background-color: var(--hacker-panel);
  border-bottom: 1px solid var(--hacker-border);
}

.hacker-table th {
  color: var(--hacker-green);
  font-weight: bold;
  text-transform: uppercase;
  font-size: 11px;
  letter-spacing: 1px;
  border-color: var(--hacker-border);
}

.hacker-table td {
  border-color: var(--hacker-border);
}

.hacker-table tr:hover {
  background-color: rgba(0, 255, 65, 0.05);
}

.hacker-table tr.el-table__row--striped {
  background-color: rgba(0, 0, 0, 0.1);
}

/* 分页控件 */
.pagination-wrapper {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.hacker-pagination {
  color: var(--hacker-text);
}

.hacker-pagination .el-pagination__total {
  color: var(--hacker-text);
  font-size: 11px;
}

.hacker-pagination .el-pagination__sizes .el-input .el-input__inner {
  background-color: var(--hacker-panel-dark);
  border-color: var(--hacker-border);
  color: var(--hacker-text);
  font-size: 11px;
}

.hacker-pagination .el-pagination__prev,
.hacker-pagination .el-pagination__next,
.hacker-pagination .el-pagination__number {
  background-color: var(--hacker-panel-dark);
  border-color: var(--hacker-border);
  color: var(--hacker-text);
  font-size: 11px;
}

.hacker-pagination .el-pagination__prev:hover,
.hacker-pagination .el-pagination__next:hover,
.hacker-pagination .el-pagination__number:hover {
  border-color: var(--hacker-green);
  color: var(--hacker-green);
}

.hacker-pagination .el-pagination__number.is-current {
  background-color: var(--hacker-green);
  border-color: var(--hacker-green);
  color: var(--hacker-dark);
}

/* 黑客风格对话框 */
.hacker-dialog {
  background-color: var(--hacker-panel);
  border: 1px solid var(--hacker-border);
  border-radius: 4px;
  box-shadow: 0 8px 24px rgba(0, 255, 65, 0.1);
}

.dialog-header-hacker {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.dialog-dots {
  display: flex;
  gap: 4px;
}

.dialog-dots .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: var(--hacker-green);
  animation: dotPulse 2s infinite alternate;
}

.dialog-dots .dot:nth-child(2) {
  animation-delay: 0.3s;
}

.dialog-dots .dot:nth-child(3) {
  animation-delay: 0.6s;
}

.dialog-title-text {
  color: var(--hacker-green);
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 1px;
  margin: 0;
}

/* 黑客风格表单 */
.hacker-form .el-form-item__label {
  color: var(--hacker-text);
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.dialog-footer-hacker {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

/* 数字雨背景效果 */
.matrix-rain {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.matrix-char {
  position: absolute;
  color: rgba(0, 255, 65, 0.08);
  font-family: 'Courier New', monospace;
  opacity: 0;
  animation: matrixRain linear infinite;
  transform-origin: 0 0;
}

/* 系统日志面板 */
.system-log-panel {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 350px;
  height: 200px;
  background-color: var(--hacker-panel-dark);
  border: 1px solid var(--hacker-border);
  border-bottom: none;
  border-right: none;
  border-radius: 4px 0 0 0;
  box-shadow: -2px -2px 10px rgba(0, 255, 65, 0.05);
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  background-color: var(--hacker-panel);
  border-bottom: 1px solid var(--hacker-border);
  font-size: 11px;
}

.log-title {
  color: var(--hacker-green);
  text-transform: uppercase;
  letter-spacing: 1px;
}

.clear-log {
  color: var(--hacker-text);
  cursor: pointer;
  transition: color 0.3s ease;
}

.clear-log:hover {
  color: var(--hacker-green);
}

.log-content {
  flex: 1;
  overflow-y: auto;
  padding: 5px 10px;
  font-size: 10px;
  line-height: 1.4;
}

.log-entry {
  display: flex;
  gap: 8px;
  margin-bottom: 2px;
}

.log-time {
  color: var(--hacker-green-dark);
  font-weight: bold;
  min-width: 60px;
}

.log-message {
  color: var(--hacker-text);
  flex: 1;
}

/* 动画效果 */
@keyframes matrixRain {
  0% {
    transform: translateY(-10%) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 0.5;
  }
  90% {
    opacity: 0.5;
  }
  100% {
    transform: translateY(110%) rotate(10deg);
    opacity: 0;
  }
}

@keyframes dotPulse {
  0% {
    opacity: 0.5;
    transform: scale(0.8);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: var(--hacker-panel-dark);
}

::-webkit-scrollbar-thumb {
  background: var(--hacker-green-dark);
  border: 1px solid var(--hacker-green-glow);
}

::-webkit-scrollbar-thumb:hover {
  background: var(--hacker-green);
  box-shadow: 0 0 8px var(--hacker-green-glow);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .system-log-panel {
    width: 100%;
    height: 120px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 5px;
    align-items: flex-start;
  }
  
  .hacker-table {
    font-size: 11px;
  }
  
  .hacker-table th {
    font-size: 10px;
  }
}
</style>